package com.xhu.collegestudentrentalsystem.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhu huilin
 * @date 2023/2/17 20:20
 *
 *  Swagger生成、描述和调用RestFul接口 框架配置
 */
@Configuration
@EnableOpenApi
public class SwaggerConfig {

    /**
     * 配置信息，让Swagger2被SpringBoot管理
     */
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                // 指定构建api文档的详细信息
                .apiInfo(getApiInfo())
                .select()
                // 指定要生成api接口的包的路径，只有在指定包下的内容才会被展示
                .apis(RequestHandlerSelectors.basePackage("com.xhu"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 构建详细的api信息
     */
    public ApiInfo getApiInfo(){
        return new ApiInfoBuilder()
                // 页面的标题
                .title("校园租赁系统")
                // 设置接口的中描述
                .description("校园租赁系统api文档")
                // 文档书写人的联系方式
                .contact(new Contact("朱慧琳", null, "3235934730@qq.com"))
                // 设置文档的版本号
                .version("1.0")
                // 构建
                .build();
    }

    /**
     解决Swagger3.0 和Spring Boot 2.6.x 兼容问题，复制该段即可
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(
                    Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider
                        || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void
            customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

}
